﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace Utils.Helper
{
    public class DateTimeHelper
    {
        public static void BaseToUtcTime<T>(T t, bool recursive = false)
        {
            Type type = typeof(T);
            BaseToUtcTime(type, t, recursive);
        }

        /// <summary>
        /// 时间上下文转为UTC
        /// </summary>
        /// <param name="type"></param>
        /// <param name="instance"></param>
        /// <param name="recursive">递归</param>
        public static void BaseToUtcTime(Type type, object instance, bool recursive = false)
        {
            if (type == null)
                return;
            if (instance == null)
                return;

            System.Reflection.PropertyInfo[] properties = type.GetProperties();

            string dateTimeTypeName = typeof(DateTime).FullName;
            foreach (var prop in properties)
            {
                var propInstance = prop.GetValue(instance);
                if (propInstance == null)
                    continue;

                //递归
                RecursiveBaseToUtcTime(prop, propInstance, recursive);

                if (prop.PropertyType.FullName != dateTimeTypeName)
                    continue;

                var value = (DateTime)propInstance;
                if (value.Kind == DateTimeKind.Utc)
                    continue;

                var newValue = DateTime.SpecifyKind(value, DateTimeKind.Utc);
                prop.SetValue(instance, newValue);
            }
        }

        private static void RecursiveBaseToUtcTime(System.Reflection.PropertyInfo prop, object instance, bool recursive)
        {
            if (!recursive)
                return;

            //Enumerable
            //Array
            //Dictionary
            var isEnumerabble = prop.PropertyType.GetInterfaces().Where(s => s.IsGenericType && s.Name.Contains("IEnumerable")).Any();
            if (!isEnumerabble)
                return;

            var iteror = instance as IEnumerable;
            foreach (var item in iteror)
            {
                BaseToUtcTime(prop.PropertyType, instance, recursive);
            }
        }
    }
}
